#!/usr/bin/env python2
#
# Copyright (c) 2016,2018 Cisco and/or its affiliates.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
from string import Template

from jni_impl_gen import generate_jni_impl
from jni_msg_handlers_gen import generate_jni_handlers
from jni_type_handlers_gen import generate_type_handlers
from jvpp_model import is_control_ping, is_dump, is_request, is_control_ping_reply


def generate_jni(work_dir, model, logger):
    logger.debug("Generating jvpp C for %s" % model.json_api_files)
    plugin_name = model.plugin_name
    messages = model.messages

    with open("%s/jvpp_%s_gen.h" % (work_dir, plugin_name), "w") as f:
        f.write(_JVPP_C_TEMPLATE.substitute(
            json_filename=model.json_api_files,
            class_cache=_generate_class_cache(plugin_name, messages),
            api_verification=_generate_api_verification(messages),
            type_handlers=generate_type_handlers(model, logger),
            jni_implementations=generate_jni_impl(model),
            msg_handlers=generate_jni_handlers(model),
            handler_registration=_generate_handler_registration(messages)))

_JVPP_C_TEMPLATE = Template("""/**
 * This file contains JNI bindings for jvpp Java API.
 * It was generated by jni_gen.py based on $json_filename.
 */
$class_cache

$api_verification

// Type handlers
$type_handlers

// JNI bindings
$jni_implementations

// Message handlers
$msg_handlers

$handler_registration
""")


def _generate_class_cache(plugin_name, messages):
    references = []
    for msg in messages:
        if is_control_ping(msg) or is_control_ping_reply(msg):
            # Skip control_ping managed by jvpp registry.
            continue
        references.append((
            msg.java_name_lower,
            'io/fd/jvpp/%s/dto/%s' % (plugin_name, msg.java_name_upper)
        ))

    references.append(('callbackException', 'io/fd/jvpp/VppCallbackException'))

    return _CLASS_CACHE_TEMPLATE.substitute(
        class_references=_generate_class_references(references),
        create_references=_generate_create_references(references),
        delete_references=_generate_delete_references(references)
    )

_CLASS_CACHE_TEMPLATE = Template("""
// JAVA class reference cache
$class_references

static int cache_class_references(JNIEnv* env) {
$create_references
    return 0;
}

static void delete_class_references(JNIEnv* env) {
$delete_references
}""")


def _generate_class_references(references):
    return "\n".join("jclass %sClass;" % r[0] for r in references)


def _generate_create_references(references):
    items = []
    for r in references:
        items.append(_CREATE_GLOBAL_REF_TEMPLATE.substitute(
            ref_name=r[0],
            fqn_name=r[1]
        ))
    return "".join(items)

_CREATE_GLOBAL_REF_TEMPLATE = Template("""
    ${ref_name}Class = (jclass)(*env)->NewGlobalRef(env, (*env)->FindClass(env, "${fqn_name}"));
    if ((*env)->ExceptionCheck(env)) {
        (*env)->ExceptionDescribe(env);
        return JNI_ERR;
    }""")


def _generate_delete_references(references):
    items = []
    for r in references:
        items.append(_DELETE_CLASS_INVOCATION_TEMPLATE.substitute(ref_name=r[0]))
    return "".join(items)

_DELETE_CLASS_INVOCATION_TEMPLATE = Template("""
    if (${ref_name}Class) {
        (*env)->DeleteGlobalRef(env, ${ref_name}Class);
    }""")


def _generate_api_verification(messages):
    items = []
    for msg in messages:
        items.append("_(%s_%s) \\" % (msg.name, msg.crc))
    return _API_VERIFICATION_TEMPLATE.substitute(messages="\n".join(items))

_API_VERIFICATION_TEMPLATE = Template("""
// List of supported API messages used for verification
#define foreach_supported_api_message \\
$messages
""")


def _generate_handler_registration(messages):
    """
    Generates msg handler registration for all messages except for dumps and requests.
    :param messages: collection of VPP API messages.
    """
    handlers = []
    for msg in messages:
        if is_control_ping(msg) or is_control_ping_reply(msg):
            # Skip control_ping managed by jvpp registry.
            continue
        if is_dump(msg) or is_request(msg):
            continue
        name = msg.name
        crc = msg.crc
        handlers.append("_(%s_%s, %s) \\" % (name, crc, name))
    return _HANDLER_REGISTRATION_TEMPLATE.substitute(handlers="\n".join(handlers))

_HANDLER_REGISTRATION_TEMPLATE = Template("""
// Registration of message handlers in vlib
#define foreach_api_reply_handler \\
$handlers
""")
